package cn.oowoo.rabbitmq.ttl;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Author ZhangBin
 * @Date 2021/5/8 15:18
 * @Description: 消息过期测试-生产者
 *
 **/
public class TTLConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();
        channel.basicQos(0,1,false);//每次取一个，不一次性拿出

        // 创建消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @SneakyThrows
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                Thread.sleep(2000);//配合channel.basicQos实现每两秒钟消费一条，最多能消费3~5条消息队列就会过期，里面的其他消息将会被丢弃
                System.out.println("Received message : " + msg);
                channel.basicAck(envelope.getDeliveryTag(),true);
            }
        };

        /**
         * autoAck= false :关闭自动确认，也就是开启手动确认
         * 开始获取消息，注意这里开启了手工应答（关闭自动应答）
         * String basicConsume(String queue, boolean autoAck, Consumer callback)
         *
         */
        channel.basicConsume(RabbitConfig.QUEUE_TTL_NAME, false,consumer);
    }

}
